package com.wpr.shop.configure.interceptor;

import com.wpr.shop.modules.global.validate.ReturnCode;
import com.wpr.shop.utils.InterceptorUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandles;

/**
 * describe:
 *
 * @author zhanglisheng
 * @date 2018/10/25
 */
@Component
public class HttpRequestInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (null != handler && handler instanceof HandlerMethod) {
            long upTime = System.currentTimeMillis();
            request.setAttribute("upTime", upTime);

            String requstParamsJson = InterceptorUtils.getRequestData(request);
            request.setAttribute("requstParamsJson", requstParamsJson);
            return true;
        } else {
            return false;
        }
    }



    @SuppressWarnings("unchecked")
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        String systemId = (String) request.getAttribute("systemId"); //登陆账号
        Object tempUpTime = request.getAttribute("upTime");
        String requstParamsJson = (String) request.getAttribute("requstParamsJson");

        systemId = systemId != null ? systemId : "";
        long upTime = tempUpTime != null ? Long.parseLong(tempUpTime.toString()) : 0;
        requstParamsJson = requstParamsJson != null ? requstParamsJson : "";

        String responseDataJson = InterceptorUtils.getResponseDataJson(response);
        String headerJson = InterceptorUtils.getHeaderJson(request);

        //无任何返回值，系统异常
        if (StringUtils.isBlank(responseDataJson)) {
            responseDataJson = InterceptorUtils.setResponse(ReturnCode.ERROR_GENER, response);
        }
        String statisticsLog = InterceptorUtils.getStatisticsLog(request, systemId, headerJson, requstParamsJson, responseDataJson, upTime);
        LOGGER.info(statisticsLog);

    }


}
